package dry.example.runner;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.StandardServletEnvironment;

import java.util.HashMap;
import java.util.Map;

@Component
public class BRunner implements ApplicationRunner {

    @Autowired
    Environment environment;

    @Override
    public void run(ApplicationArguments args) {
        getEnvironment();
    }

    public void getEnvironment() {
        Map<String, Map<String, String>> result = new HashMap<>(16);
        StandardServletEnvironment env = (StandardServletEnvironment) environment;
        for (PropertySource<?> source : env.getPropertySources()) {
            String name = source.getName();
            if (!name.startsWith("applicationConfig")) {
                continue;
            }
            int start = name.indexOf("/");
            int end = name.indexOf(".properties");
            name = name.substring(start + 1, end);
            Map<String, String> kv = new HashMap<>(16);
            Object s = source.getSource();
            if (s instanceof Map) {
                Map<String, Object> temp = (Map<String, Object>) s;
                for (Map.Entry<String, Object> e : temp.entrySet()) {
                    String key = e.getKey();
                    String value = env.getProperty(key);
                    kv.put(key, value);
                }
            }
            result.put(name, kv);
        }
        System.out.println(result);
    }

}